package com.chinasoft.reposearch.util;

import com.fasterxml.jackson.databind.*;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.List;

@Component
public class JacksonUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        // 配置 ObjectMapper
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * JSON字符串转对象
     */
    public static <T> T jsonToObject(String json, Class<T> clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            throw new RuntimeException("JSON转换失败", e);
        }
    }

    /**
     * 对象转JSON字符串
     */
    public static String objectToJson(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            throw new RuntimeException("对象转JSON失败", e);
        }
    }

    /**
     * JSON文件转对象
     */
    public static <T> T fileToObject(String filePath, Class<T> clazz) {
        try {
            return objectMapper.readValue(new File(filePath), clazz);
        } catch (Exception e) {
            throw new RuntimeException("文件读取失败: " + filePath, e);
        }
    }

    /**
     * JSON文件转对象列表
     */
    public static <T> List<T> fileToObjectList(String filePath, Class<T> clazz) {
        try {
            JavaType type = objectMapper.getTypeFactory()
                    .constructCollectionType(List.class, clazz);
            return objectMapper.readValue(new File(filePath), type);
        } catch (Exception e) {
            throw new RuntimeException("文件读取失败: " + filePath, e);
        }
    }
}
